/**
 * <p>Copyright:Copyright(c) 2019</p>
 * <p>Company:Professional</p>
 * <p>Package:ces.org.course.event</p>
 * <p>File:FileUploadListener.java</p>
 * <p>类更新历史信息</p>
 *
 * @todo chanlong(陈龙) 创建于 May 17, 2019 4:24:21 PM
 */
package ces.org.course.api.event;

import java.io.File;
import java.nio.file.Paths;

import javax.validation.constraints.NotNull;

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import ces.org.course.api.entity.DictionaryEntity;
import ces.org.course.api.service.DictionaryService;
import cn.hutool.core.io.FileUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;

/**
 * <p>描述: </p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date May 17, 2019 4:24:21 PM
 * @version 1.0.2019
 */
@Component
@Builder
@AllArgsConstructor
public class FileUploadListener {

    // 文件创建时触发
    public void onFileCreate(final File file) {
        service.put(DictionaryEntity.CACHE_KEY, file);
    }

    // 文件删除时触发
    public void onFileDelete(final File file) {
        service.clear(DictionaryEntity.CACHE_KEY);

        FileUtil.loopFiles(file.getParentFile()).forEach(f -> {
            if (null != f && "xml".equals(FileUtil.extName(f))) service.put(DictionaryEntity.CACHE_KEY, f);
        });
    }

    // 文件修改时触发
    public void onFileChange(final File file) {
        service.put(DictionaryEntity.CACHE_KEY, file);
    }

    @NotNull
    private final DictionaryService service;// 需要 compile在重试。就可以连接过去


    @EventListener()
    public void listener(final FileUploadEvent event) {
        System.out.println(event.getMessage().getMessage());
        String path = event.getMessage().getPath();
        if(event.getMessage().getChangeMethod().equals("event")){
            onFileCreate(Paths.get(path).toFile());
        }
    }

}
